import { onBeforeUnmount, ref } from 'vue'

export default function useKeyEnter(fn: any) {
  const isEnter = ref(false)
  const handleKeyDown = (event: KeyboardEvent) => {
    if (event.key === 'Enter' && !isEnter.value) {
      isEnter.value = true
      fn(event)
    }
  }
  const handleKeyUp = (event: KeyboardEvent) => {
    if (event.key === 'Enter') {
      isEnter.value = false
    }
  }
  window.addEventListener('keydown', handleKeyDown)
  window.addEventListener('keyup', handleKeyUp)

  onBeforeUnmount(() => {
    window.removeEventListener('keydown', handleKeyDown)
    window.removeEventListener('keyup', handleKeyUp)
  })
}
